#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
#include <windows.h>

#define WIDTH 40
#define HEIGHT 20

int birdX, birdY;
int wallX, wallY;
int score = 0;
int gameOver = 0;

void gotoxy(int x, int y) {
    COORD coord;
    coord.X = x;
    coord.Y = y;
    SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), coord);
}

void drawBorder() {
    int i;
    for (i = 0; i < WIDTH; i++) {
        gotoxy(i, 0);
        printf("#");
        gotoxy(i, HEIGHT);
        printf("#");
    }

    for (i = 0; i < HEIGHT; i++) {
        gotoxy(0, i);
        printf("#");
        gotoxy(WIDTH, i);
        printf("#");
    }
}

void drawBird() {
    gotoxy(birdX, birdY);
    printf("@");
}

void eraseBird() {
    gotoxy(birdX, birdY);
    printf(" ");
}

void drawWall() {
    int i;
    for (i = 1; i < HEIGHT - 1; i++) {
        gotoxy(wallX, i);
        printf("#");
    }
}

void eraseWall() {
    int i;
    for (i = 1; i < HEIGHT - 1; i++) {
        gotoxy(wallX, i);
        printf(" ");
    }
}

void updateBirdPosition() {
    if (kbhit()) {
        char ch = getch();
        if (ch == ' ') {
            birdY--;
        }
    } else {
        birdY++;
    }
}

void updateWallPosition() {
    wallX--;
    if (wallX < 1) {
        wallX = WIDTH - 1;
        wallY = rand() % (HEIGHT - 3) + 1;
    }
}

void checkCollision() {
    if (birdX == wallX && (birdY <= wallY || birdY >= wallY + 3)) {
        gameOver = 1;
    } else if (birdY <= 0 || birdY >= HEIGHT) {
        gameOver = 1;
    } else {
        score++;
    }
}

void showScore() {
    gotoxy(WIDTH + 5, HEIGHT / 2);
    printf("Score: %d", score);
}

int main() {
    system("cls");
    birdX = 10;
    birdY = HEIGHT / 2;
    wallX = WIDTH - 1;
    wallY = rand() % (HEIGHT - 3) + 1;

    while (!gameOver) {
        drawBorder();
        eraseBird();
        drawBird();
        eraseWall();
        drawWall();
        updateBirdPosition();
        updateWallPosition();
        checkCollision();
        showScore();
        Sleep(50);
    }

    system("cls");
    gotoxy(WIDTH / 2 - 5, HEIGHT / 2);
    printf("Game Over!");
    gotoxy(WIDTH / 2 - 7, HEIGHT / 2 + 1);
    printf("Your score: %d", score);

    return 0;
}